package cn.lh.util;

import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * @描述:
 * @版权: Copyright (c) 2023
 * @作者: linhong
 * @版本: 1.0.0
 * @创建时间: 2023/12/29
 */
public class ASEUtil {

    //算法
    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";

    private static final String KEY = "QKEw7zb9meyVUjwh";

    public static void main(String[] args)throws Exception  {
        String key = geneKey();
//
//        System.err.println(key);

        String content = "Tfi@123456789";
        String aesEncrypt = aesEncrypt(content, KEY);
        System.err.println("aesEncrypt: " +aesEncrypt);

        String aesDecrypt = aesDecrypt(aesEncrypt, KEY);
        System.err.println("aesDecrypt: " + aesDecrypt);

    }

    public static  String geneKey() throws Exception {
        //获取一个密钥生成器实例
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128);
        SecretKey secretKey = keyGenerator.generateKey();
        return Base64.encodeBase64String(secretKey.getEncoded());
    }


    /**
     * AES加密
     * @param content 待加密的内容
     * @param encryptKey 加密密钥
     * @return 加密后的byte[]
     * @throws Exception
     */
    public static String aesEncrypt(String content, String encryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
        return Base64.encodeBase64String(cipher.doFinal(content.getBytes("utf-8")));
    }

    /**
     * AES解密
     * @param content 待解密的string
     * @param decryptKey 解密密钥
     * @return 解密后的String
     * @throws Exception
     */
    public static String aesDecrypt(String content, String decryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);

        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
        byte[] decryptBytes = cipher.doFinal(Base64.decodeBase64(content));
        return new String(decryptBytes);
    }

}
